package com.yutian.user.demo.service;

import com.yutian.user.demo.dao.model.User;
import com.yutian.user.demo.mapper.UserMapper;
import com.yutian.user.demo.vo.UserAddReq;
import com.yutian.user.demo.vo.UserInfo;
import com.yutian.user.demo.vo.UserUpdateReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public long add(UserAddReq req){
        User user = User.builder()
                .name(req.getName())
                .password(req.getPassword())
                .stuNumber(req.getStuNumber())
                .build();
        userMapper.insert(user);
        return user.getId();
    }

    public UserInfo get(long id){
        User user = userMapper.get(id);
        if(null == user){
            // throw new RuntimeException("user cannot be found by id=" + id);
            return null;
        }
        return UserInfo.builder()
                .id(user.getId())
                .name(user.getName())
                .stuNumber(user.getStuNumber())
                .build();
    }

    public void update(UserUpdateReq req) {
        User user = User.builder()
                .id(req.getId())
                .name(req.getName())
                .password(req.getPassword())
                .stuNumber(req.getStuNumber())
                .build();
        userMapper.update(user);
    }

    public void delete(long id) {
        userMapper.deleteById(id);
    }

    public List<UserInfo> list(String nameLike) {
        List<User> users = userMapper.list(nameLike);
        if(CollectionUtils.isEmpty(users)){
            return new ArrayList<>();
        }
        return users.stream().map(user -> {
            return UserInfo.builder()
                    .id(user.getId())
                    .name(user.getName())
                    .stuNumber(user.getStuNumber())
                    .build();
        }).collect(Collectors.toList());
    }
}
